初学网络编程,需要了解的tcp的socket的小例子
private void AcceptMessage()
{
while (true)
{
try
{
NetworkStream netStream = new NetworkStream(newSocket);
byte[] datasize = new byte[4];
netStream.Read(datasize, 0, 4);
int size = System.BitConverter.ToInt32(datasize, 0); //得到缓冲区数据的大小
Byte[] message = new byte[size];
int dataleft = size;
int start = 0;
while (dataleft > 0) //逐字节读取数据
{
int recv = netStream.Read(message, start, dataleft);
start = recv;
dataleft -= recv;
}
this.rtbAccept.Rtf = System.Text.Encoding.Unicode.GetString(message);
}
catch
{
this.lbState.Items.Add("与客户断开连接");
break;
}
}
}
private void btnSend_Click(object sender, EventArgs e)
{
string str = this.rtbSend.Rtf;
int i = str.Length;
if (i == 0)
{
return;
}
else
{
//因为str为Unicode编码,每个字符占2字节,所以实际字节数应*2
i *= 2;
}
byte[] datasize = new byte[4];
//将32位整数值转换为字节数组
datasize = System.BitConverter.GetBytes(i);
byte[] sendbytes = System.Text.Encoding.Unicode.GetBytes(str);
try
{
NetworkStream netStream = new NetworkStream(newSocket);
netStream.Write(datasize, 0, 4);
netStream.Write(sendbytes, 0, sendbytes.Length);
netStream.Flush();
this.rtbSend.Rtf = "";
}
catch
{
MessageBox.Show("无法发送!");
}
}
private void btnStopListen_Click(object sender, EventArgs e)
{
this.btnStartListen.Enabled = true;
try
{
socket.Shutdown(SocketShutdown.Both); //此处总产生异常
socket.Close();
if (newSocket.Connected)
{
newSocket.Close();
thread.Abort();
this.lbState.Items.Add("停止监听,与客户断开连接");
}
}
catch
{
MessageBox.Show("监听尚未开始,关闭无效!");
}
}
评论